import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import styles from './index.less';
import _ from 'lodash';

import { TRDefault } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { DimensionalSort, PageLoading } from '@/components';
import { TjChart, TjCollapse, TjSelect } from '@/pages/ETrade/components';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { getCssVariableValue } from '@/utils/utils';
// import ChartBox from '../ChartBox';

import BaseTable from './BaseTable';
import LeftTable from '../LeftTable';
import {
  chartsMap,
  // chartsMap_subpage_isSDN,
  Doubel_yAxis_serise,
  Doubel_yAxis_title,
  indexMap,
  OPTION_KEY,
  SELECT_DATA,
  liaoNingTableHead,
  liaoningHeaderMap,
  liaoNingTableHead1,
  liaoningHeaderMap1,
} from './helper';
import {
  _getTotalStatementEnergyPrice,
  dealDataMap,
  getNewFlagDataSource,
  newForMater,
  chooseData,
} from './utils';
import { formatJson } from './utils';
import { getSpotResumeAnalysisDataNew, querySpotResumeAnalysisOverall } from '../../services';
import Title from '../Title';
import { useSetState } from 'ahooks';
import moment from 'moment';
import { DatePicker } from 'antd';
import { useThemeChange } from '@/hooks';

const defaultParams = ['交易单元', '日期'];

export default forwardRef(
  (
    { tag, queryForm, queryUrlForm, stations, dimensionEnum, hasUrlData, changeSearchBtnLoading },
    ref,
  ) => {
    const [realData, setRealData] = useState([]); // 记录echars数据
    const [sumaryData, setSumaryData] = useState([]); // 概括数据
    const [tableData, setTableData] = useState([]); // 表格数据
    const [tableHead, setTableHead] = useState([]); // 表头数据
    const [crumbsName, setCrumbsName] = useState(''); // echarts图表面包屑
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [param, setParam] = useState(defaultParams); //灵活聚合项
    const [filterOptions, setFilterOptions] = useState([]);
    const [dateTime, setDateTime] = useState(); //父维度筛选 时间
    const [echartsParam, setEchartsParam] = useSetState({
      date: '',
      stationName: '',
      timeOrder: '',
    }); //图表筛选参数

    useImperativeHandle(ref, () => ({
      onFetch,
      onExport,
    }));

    useEffect(() => {
      if (!tableData.length) return;
      onFetch();
    }, [param]);

    useEffect(() => {
      if (!tableData.length) return;
      repaint();
    }, [echartsParam, tableData]);

    //根据筛选参数 重绘图表
    const repaint = () => {
      const dic = param.slice(0, param.length - 1);
      const value = dic.map((i) => echartsParam[OPTION_KEY[i]]);
      let chartData;
      const getChartData = (arr, v) => {
        arr.map((i) => {
          if (i.name === v) {
            value.shift();
            if (value.length === 0) {
              chartData = i;
            } else {
              getChartData(i?.children || [], value[0]);
            }
          }
        });
      };
      if (value?.[0]) {
        getChartData(tableData, value[0]);
      }
      if (chartData) {
        getEcharsData(chartData);
      }
    };

    /** 数据处理 */
    async function onFetch() {
      setTableData([]);
      setSumaryData([]);
      changeSearchBtnLoading(true);
      const { stationIds, provinceId, tag, startDate, endDate, dimension, groupIds, pointNum } =
        queryForm;
      const params = {
        stationIds,
        provinceId,
        tag,
        startDate,
        endDate,
        dimension,
        groupIds,
        pointNum,
      };
      await Promise.all([onFetchData(params), onFetchSumarys(params)]).finally(() =>
        changeSearchBtnLoading(false),
      );
    }

    const buildNewServerParams = (params) => {
      return {
        flexAggrBody: {
          order: param,
          orderSize: SELECT_DATA.length,
          needTotal: true,
          timeOrder: params.pointNum,
        },
        spotResumptionInProvinceBody: {
          ...params,
        },
      };
    };

    async function onFetchData(params) {
      let newParams = params;
      setLoading(true);

      // 构建新接口需要的参数
      newParams = buildNewServerParams(newParams);

      const res = await getSpotResumeAnalysisDataNew(newParams).catch(() => setLoading(false));
      if (res?.statusCode === HttpCode.SUCCESS) {
        // const data = getFlagDataSource(res.data.tableData || [], params);
        const data = getNewFlagDataSource(res?.data || [], param, queryForm.pointNum);
        getFilterOptions(data);
        setTableData(data);
        // setTableHead(res?.data?.head);
        if (tag === '1') {
          const newHead = res?.data?.head.filter((item) => !item.includes('阻塞及偏差'));
          newHead.push('偏差');
          setTableHead(newHead);
        } else {
          setTableHead(res?.data?.head);
        }
      } else {
        setError(res?.message || '系统异常');
      }
      setLoading(false);
    }

    //获取各项筛选框数据源
    const getFilterOptions = (data, _echartsParam = {}, oIndex = -1) => {
      if (!data.length) return;

      const _params = {
        ...echartsParam,
        ..._echartsParam,
      };
      const filterData = _.cloneDeep(data).splice(1);
      const _filterOptions = [];
      (function reduce(data, index = 0) {
        const options = [];
        data.forEach((t, i) => {
          //判断是否为最后一个维度   ps:最后一个维度无需下拉选项
          if (!t?.children?.length) return;
          options.push(t.title);
          //取默认首项
          if (oIndex < index && i === 0) {
            _params[OPTION_KEY[param[index]]] = t.title;
          }
          //取对应维度子项
          if (t.title === _params?.[OPTION_KEY[param[index]]]) {
            setEchartsParam({
              [OPTION_KEY[param[index]]]: t.title,
            });
            reduce(t.children, index + 1);
          }
        });

        _filterOptions[index] = options;
      })(filterData);
      setFilterOptions(_filterOptions);

      //处理日期可选区间
      const dateList = _filterOptions[param.indexOf('日期')];
      const _startDate = dateList?.[0];
      const _endDate = dateList?.[dateList.length - 1];
      const _datetime = [moment(_startDate), moment(_endDate)];
      setDateTime(_datetime);
    };

    async function onFetchSumarys(params) {
      // 概览数据
      const res = await querySpotResumeAnalysisOverall(params).catch(() => {});
      if (res?.statusCode === HttpCode.SUCCESS) {
        setSumaryData(res.data);
      } else {
        setError(res?.message || '系统异常');
      }
    }

    const onExport = () => {
      let filename = '现货复盘分析';
      if (queryForm.regions) {
        filename = `${queryForm.regions}${queryForm.startDate
          .split('-')
          .join('')}-${queryForm.endDate.split('-').join('')}`;
      }
      const params = {
        header: ['维度'],
        data: [],
        filename,
      };
      const dataFalt = [];
      tableData?.map((x) => {
        dataFalt.push(x);
        (x?.children || []).map((y) => {
          dataFalt.push(y);
          (y?.children || []).map((z) => {
            dataFalt.push(z);
          });
        });
      });
      const filterVal = ['name'];
      tableHead?.forEach((item) => {
        params.header.push(item);
        // filterVal.push(liaoningHeaderMap[item]);
        // 1-测算数据 2-结算数据
        if (tag === '1') {
          filterVal.push(liaoningHeaderMap1[item]);
        } else {
          filterVal.push(liaoningHeaderMap[item]);
        }
      });
      params.data = formatJson(filterVal, dataFalt);
      export_json_to_excel(params);
    };

    /** methods */
    // 获取echars图表数据
    const getEcharsData = (value) => {
      const data = tableData || []; // 表格原始数据
      const dataMap = {};
      const { echarsData, XAXIS, isSDN } = chooseData(data, value);
      if (!isSDN) {
        new Set(Object.values(chartsMap).flat()).map((t) => {
          if (t.includes('_')) return; //在下方计算
          dataMap[t] = newForMater(echarsData, t);
        });
        //计算
        dataMap._averagePrice = _getTotalStatementEnergyPrice(
          echarsData,
          'totalStatementEnergyPrice',
        ); // 算术均价
        dataMap.spotSettlementElectricityQuantity = echarsData.map((item) => {
          const dayahead = Number(item.provincialDayaheadStatementQuantity) || 0;
          const realtime = Number(item.provincialRealtimeStatementQuantity) || 0;
          return parseFloat((dayahead + realtime).toFixed(3));
        });
        // 现货结算电量
      } else {
        //子页面96|24点维度
        if (echarsData?.[0]?.children?.[0]?.children?.length) {
          // dealDataMap(chartsMap_subpage_isSDN, echarsData[0]?.children, dataMap);
        }
      }
      setRealData({
        ...dataMap,
        XAXIS,
      });
    };
    /**图表配置*/
    const getChartOption = ([title, data], dataSource) => {
      const chartData = [],
        _yAxis = [
          {
            type: 'value',
            nameTextStyle: {
              color: getCssVariableValue('--chart-font-color'),
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
          },
        ];
      dataSource.XAXIS.map((x, i) => {
        const temp = {};
        data.map((t) => {
          const a = t.split('_');
          //屏蔽同名 不同系列名
          if (a[0] && a[1]) {
            temp[t] = dataSource[a[0]][i];
            return;
          }
          temp[t] = dataSource[t][i];
        });
        chartData.push({
          ...temp,
          XAXIS: x,
        });
      });
      if (Doubel_yAxis_title.includes(title)) {
        _yAxis.push({
          type: 'value',
          splitLine: {
            show: false,
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
        });
      }
      const _series = data.map((t) => {
        const { props, ...others } = _.cloneDeep(indexMap[t]);
        if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
          props.yAxisIndex = 1;
        }
        return {
          dataIndex: t,
          props,
          ...others,
        };
      });

      return {
        grid: { top: 20, left: 48, right: 58, bottom: 50 },
        series: _series,
        dataset: {
          source: chartData,
          dimensions: ['XAXIS', ...data],
        },
        tooltip: {},
        legend: {
          textStyle: {
            color: getCssVariableValue('--chart-legend-color'),
          },
        },
        xAxis: [
          {
            type: 'category',
            axisLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisTick: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
            axisPointer: {
              type: 'line',
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
          },
        ],
        yAxis: _yAxis,
      };
    };

    /** render */
    const _getEchartsData = () => {
      const loopData = Object.entries(chartsMap);

      return (
        <div className={styles.chartsRender}>
          {loopData.map((t, i) => {
            return (
              <div
                key={i}
                style={{
                  height: `calc(${Math.floor(100 / loopData.length)}%)`,
                  minHeight: 204,
                }}
              >
                <div className={styles.chartTitle}>{t[0]}</div>
                <div style={{ height: `calc(100% - 36px)` }}>
                  {/* <TjChart option={getChartOption(t, realData)} /> */}
                  {/* <ChartBox
                    t={t}
                    realData={realData}
                    doubelYAxisTitle={Doubel_yAxis_title}
                    doubelYAxisSerise={Doubel_yAxis_serise}
                    indexMap={indexMap}
                  /> */}
                  <ChartBox t={t} realData={realData} />
                </div>
              </div>
            );
          })}
        </div>
      );
    };

    const ChartBox = ({ t, realData }) => {
      const [config, setConfig] = useState();
      const { theme } = useThemeChange();

      useEffect(() => {
        if (t) {
          setConfig(getChartOption(t, realData));
        }
      }, [t]);
      useEffect(() => {
        if (t) {
          setTimeout(() => {
            setConfig(getChartOption(t, realData));
          }, 1);
        }
      }, [theme]);
      return <TjChart option={config} />;
    };

    const _polymerize = (options) => {
      setParam([...options]);
    };

    const disabledDate = (current) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };

    const onFilterChange = (value, index, key) => {
      const _echartsParam = {
        [key]: value,
      };
      getFilterOptions(tableData, _echartsParam, index);
    };

    if (loading) return <PageLoading />;
    if (error) return <TRDefault type="error" message={error} />;
    if (!tableData.length) return <TRDefault type={'empty'} />;
    return (
      <>
        <div className={styles.box}>
          <Title data={sumaryData} />
        </div>
        <div className={styles.content}>
          <TjCollapse
            leftStyles={{ padding: '0 20px 24px 0' }}
            rightStyles={{ padding: '20px 24px', width: '50%' }}
            left={
              <>
                <div className={styles.sort}>
                  <DimensionalSort
                    optionsArray={SELECT_DATA}
                    option={param}
                    onClick={_polymerize}
                  />
                </div>
                <div className={styles.tableScroll}>
                  {/* 1-测算数据 2-结算数据 */}
                  {tag === '1' ? (
                    // <BaseTable
                    //   param={param}
                    //   tableData={tableData}
                    //   tableHead={liaoNingTableHead1}
                    //   stations={stations}
                    //   queryForm={queryForm}
                    //   queryUrlForm={queryUrlForm}
                    // />
                    <LeftTable tableData={tableData} tableHead={liaoNingTableHead1} />
                  ) : (
                    // <BaseTable
                    //   param={param}
                    //   tableData={tableData}
                    //   tableHead={liaoNingTableHead}
                    //   stations={stations}
                    //   queryForm={queryForm}
                    //   queryUrlForm={queryUrlForm}
                    // />
                    <LeftTable tableData={tableData} tableHead={liaoNingTableHead} />
                  )}
                </div>
              </>
            }
            right={
              <>
                <div className={styles.filter_group}>
                  <div className={styles.flex}>
                    {param.map((t, i) => {
                      if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                        {
                          return (
                            <TjSelect
                              key={i}
                              className={styles.filter_unit}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              showSearch
                              placeholder="选择交易单元"
                              onChange={(e) => {
                                onFilterChange(e, i, 'stationName');
                              }}
                              value={echartsParam.stationName}
                              options={filterOptions[i].map((t) => ({
                                label: t,
                                value: t,
                              }))}
                              filterOption={(input, option) => {
                                return (option?.label).toLowerCase().includes(input.toLowerCase());
                              }}
                            />
                          );
                        }
                      }
                      if (t === '日期' && param[param.length - 1] !== '日期') {
                        {
                          return (
                            <DatePicker
                              key={i}
                              onChange={(e) => {
                                onFilterChange(e.format('YYYYMMDD'), i, 'date');
                              }}
                              inputReadOnly
                              allowClear={false}
                              className={styles.filter_date}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              value={moment(echartsParam.date)}
                              format={'YYYYMMDD'}
                              disabledDate={disabledDate}
                            />
                          );
                        }
                      }
                      if (t === '时点' && param[param.length - 1] !== '时点') {
                        {
                          return (
                            <TjSelect
                              key={i}
                              className={styles.filter_point}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              placeholder="选择时点"
                              onChange={(e) => {
                                onFilterChange(e, i, 'timeOrder');
                              }}
                              value={echartsParam.timeOrder}
                              options={filterOptions[i].map((t) => ({
                                label: t,
                                value: t,
                              }))}
                            />
                          );
                        }
                      }
                    })}
                  </div>
                </div>
                {_getEchartsData()}
              </>
            }
          />
        </div>
      </>
    );
  },
);
